<template>
  <div class="register">
    <TopHeader />
    <el-card class="register-box">
      <div class="logo">
        <img src="/assets/logo.jpeg" alt="Logo">
      </div>
      <h2>用户注册</h2>
      <el-form
        ref="formRef"
        :model="registerForm"
        :rules="rules"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            :prefix-icon="Message"
          />
          <el-button size="small" style="margin-left:8px;" @click="onCheckEmail">检查邮箱</el-button>
        </el-form-item>
        <el-form-item prop="phoneNumber">
          <el-input
            v-model="registerForm.phoneNumber"
            placeholder="请输入手机号（选填）"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            class="register-btn" 
            :loading="loading"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
        <div class="login-link">
          已有账号？<el-button type="primary" link @click="goToLogin">立即登录</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import TopHeader from '../components/TopHeader.vue'
import { register, checkEmail } from '@/api/auth'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phoneNumber: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.confirmPassword !== '') {
      formRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 8, message: '密码长度不能小于8个字符', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const onCheckEmail = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请输入邮箱')
    return
  }
  try {
    await checkEmail({ email: registerForm.email })
    ElMessage.success('邮箱可用')
  } catch (e) {
    ElMessage.error('邮箱已被注册或无效')
  }
}

const handleRegister = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    loading.value = true
    const res = await register(registerForm)
    console.log(res)
    if (res.code === 200) {
      ElMessage.success('注册成功')
      // 存储token
      if (res.token) {
        userStore.setToken(res.token)
      }
      // 跳转到首页
      router.push('/')
    } else {
      ElMessage.error(res.message || '注册失败')
    }
  } catch (error) {
    ElMessage.error('表单验证失败，请检查输入')
    console.error('表单验证失败：', error)
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  router.push({
    path: '/lz/study/login',
    query: {
      from: 'home',
      timestamp: new Date().getTime()
    },
    hash: '#login-form'
  })
}
</script>

<style scoped>
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f2f5 0%, #e6e9f0 100%);
  padding-top: 60px;
  box-sizing: border-box;
  overflow-y: auto;
}

.register-box {
  width: 480px; /* 原为400px，提升表单宽度 */
  max-width: 95vw;
  padding: 48px 48px 32px 48px; /* 上下左右间距更舒适 */
  background: rgba(255, 255, 255, 0.97);
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.10);
  backdrop-filter: blur(12px);
  transition: transform 0.3s cubic-bezier(.4,2,.6,1);
}

@media (max-width: 600px) {
  .register-box {
    width: 98vw;
    padding: 24px 8px 16px 8px;
    border-radius: 10px;
  }
}

h2 {
  text-align: center;
  margin-bottom: 35px;
  color: var(--el-text-color-primary);
  font-size: 28px;
  font-weight: 600;
}

.logo {
  text-align: center;
  margin-bottom: 20px;
}

.logo img {
  width: 80px;
  height: 80px;
  object-fit: contain;
}

.register-btn {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  font-weight: 600;
}

.login-link {
  text-align: center;
  margin-top: 25px;
  font-size: 15px;
  color: var(--el-text-color-regular);
}

:deep(.el-input__wrapper) {
  padding: 8px 12px;
}

:deep(.el-form-item__error) {
  padding-top: 4px;
}
</style> 